<template>
  <div class="card-form-container">

    <div class="title-wrapper">
      <div class="title-content">
        <el-icon class="title-icon"><Document /></el-icon>
        <h3 class="form-title">访客名片</h3>
      </div>
      <el-tag size="small" effect="plain" type="info">联系人信息</el-tag>
    </div>
    <div v-if="useVisitorStore.selectedVisitor" class="visitor-id">
      选中访客ID: <strong>{{ useVisitorStore.selectedVisitor.digitalFingerprint }}</strong>
    </div>


    <el-form
      :model="formData"
      :rules="rules"
      ref="formRef"
      label-position="top"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="QQ" prop="qq">
        <el-input v-model="formData.qq" placeholder="请输入QQ号" />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          class="save-btn"
          @click="handleSubmit"
          :disabled="!useVisitorStore.selectedVisitor.digitalFingerprint"
          :title="
            !useVisitorStore.selectedVisitor.digitalFingerprint
              ? '请先选择访客'
              : ''
          "
        >
          保存名片
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  defineProps,
  watch,
  defineEmits,
  computed,
  onMounted,
} from "vue"; // 导入vue
import { useRoute } from "vue-router"; // 导入路由
import { Document } from "@element-plus/icons-vue"; // 导入访客图标
import type { FormInstance, FormRules } from "element-plus"; // 导入表单验证
import { ElMessage, ElMessageBox } from "element-plus"; // 导入element-plus
import request from "@/utils/request"; // 导入请求
import visitorStore from "@/store/modules/visitor"; // 导入访客store

import { User } from "@element-plus/icons-vue"; // 导入访客图标
import { useUserStore } from "@/store/modules/user";

import type { UserInfo } from "@/api/user/types";
const useVisitorStore = visitorStore();

interface FormData {
  // 定义表单数据
  name: string;
  phone: string;
  qq: string;
}

interface ContactDto {
  id?: number;
  name: string;
  phone?: string;
  qq?: string;
  visitorId: string;
  companyId: number;
  createBy: number;
}

interface Props {
  // 定义props
  selectedVisitor?: {
    digitalFingerprint: string;
    realName?: string;
  };
}

const formRef = ref<FormInstance>(); // 定义表单引用

const formData = reactive<FormData>({
  // 定义表单数据
  name: "",
  phone: "",
  qq: "",
});

const visitorDisplayName = ref("未选择访客");

// 获取访客信息的方法
const updateVisitorInfo = async () => {
  const visitor = useVisitorStore.selectedVisitor;

  if (!visitor || !visitor.digitalFingerprint) {
    visitorDisplayName.value = "未选择访客";
    return;
  }

  try {
    const response = await request({
      url: "/api/v1/visitor/getFinger",
      method: "get",
      params: {
        digitalFingerprint: visitor.digitalFingerprint,
      },
    });

    const latestVisitor = response.data;

    // 更新 store 中的访客信息
    useVisitorStore.setSelectedVisitor({
      ...visitor,
      realName: latestVisitor.realName,
    });

    // 设置显示名称
    if (latestVisitor.realName && latestVisitor.realName.trim()) {
      visitorDisplayName.value = `${latestVisitor.realName} (${visitor.digitalFingerprint})`;
    } else {
      visitorDisplayName.value = visitor.digitalFingerprint;
    }
  } catch (error) {
    console.error("获取访客信息失败:", error);
    visitorDisplayName.value = visitor.digitalFingerprint;
  }
};

// 监听访客变化
watch(
  () => useVisitorStore.selectedVisitor,
  () => updateVisitorInfo(),
  { immediate: true }
);

// 组件挂载时获取信息
onMounted(() => {
  updateVisitorInfo();
});

const rules = reactive<FormRules>({
  // 定义表单验证规则
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    {
      validator: (rule, value, callback) => {
        if (!value && !formData.qq) {
          callback(new Error("手机号和QQ号至少填写一个"));
        } else if (value && !/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error("请输入正确的手机号"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  qq: [
    {
      validator: (rule, value, callback) => {
        if (!value && !formData.phone) {
          callback(new Error("手机号和QQ号至少填写一个"));
        } else if (value && !/^\d{5,11}$/.test(value)) {
          callback(new Error("请输入正确的QQ号"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const route = useRoute(); // 导入路由
const props = defineProps<Props>(); // 定义props

// 监听选中访客变化
watch(
  () => props.selectedVisitor,
  (newVisitor) => {
    if (newVisitor) {
      // 如果有真实姓名，直接填充
      if (newVisitor.realName) {
        formData.name = newVisitor.realName;
      }
      // 移除弹出输入框的逻辑，让用户直接在表单中填写
    }
  },
  { immediate: true }
);

// 在 script setup 顶部添加 emit 定义
const emit = defineEmits(["refresh"]);

// 从用户store中获取当前登录用户的部门ID（公司ID）
const userStore = useUserStore();

// 修改 handleSubmit 方法
const handleSubmit = async () => {
  try {
    // 1. 先判断联系人是否存在
    const existsResponse = await request({
      url: "/api/v1/contact/existsByVisitorId",
      method: "get",
      params: {
        visitorId: useVisitorStore.selectedVisitor.digitalFingerprint,
      },
    });

    // 2. 准备联系人数据
    const contactDto: ContactDto = {
      name: formData.name,
      phone: formData.phone || undefined,
      qq: formData.qq || undefined,
      visitorId: useVisitorStore.selectedVisitor.digitalFingerprint,
      companyId: Number(userStore.user.deptId),
      createBy: Number(userStore.user.userId),
    };

    // 3. 更新访客的真实姓名
    await request({
      url: "/api/v1/visitor/updateOrInsert",
      method: "post",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      data: new URLSearchParams({
        digitalFingerprint: useVisitorStore.selectedVisitor.digitalFingerprint,
        realName: formData.name,
      }),
    });

    // 4. 根据判断结果选择新增或更新操作
    if (existsResponse.code === 200) {
      // 联系人存在，执行更新操作
      const contacts = existsResponse.data;
      if (contacts && contacts.length > 0) {
        // 获取第一个联系人的ID
        contactDto.id = contacts[0].id;

        // 调用更新接口
        await request({
          url: "/api/v1/contact/update",
          method: "post",
          data: contactDto,
        });
        ElMessage.success("联系人信息更新成功");
      }
    } else {
      // 联系人不存在，执行新增操作
      await request({
        url: "/api/v1/contact/add",
        method: "post",
        data: contactDto,
      });
      ElMessage.success("联系人信息添加成功");
    }

    // 5. 重置表单并刷新
    resetForm();
    emit("refresh");
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error(
      error instanceof Error ? error.message : "保存失败，请重试"
    );
  }
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 可以直接使用 visitorStore.selectedVisitor 获取选中的访客信息
console.log("当前选中的访客:", visitorStore.selectedVisitor);

// 可以添加一个计算属性来判断是否可以保存
const canSave = computed(() => {
  return !!useVisitorStore.selectedVisitor.digitalFingerprint;
});
</script>

<style lang="scss" scoped>
.card-form-container {
  height: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .title-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;

    .title-content {
      display: flex;
      align-items: center;
      gap: 8px;

      .title-icon {
        font-size: 18px;
        color: #409eff;
        background: #ecf5ff;
        padding: 8px;
        border-radius: 8px;
      }

      .form-title {
        color: #303133;
        font-weight: 600;
        font-size: 16px;
        margin: 0;
      }
    }
  }

  :deep(.el-form-item__label) {
    padding-bottom: 8px;
    font-weight: 500;
  }

  .save-btn {
    width: 100%;
    height: 130%;
    padding: 12px 0;
    font-size: 14px;
    margin-top: 12px;
  }
}

.visitor-id {
  margin-bottom: 12px;
  padding: 4px;
  background-color: #f0f9eb;
  border: 1px solid #d9e8c4;
  border-radius: 4px;
  color: #4caf50;
  font-weight: bold;
  font-size: 14px;
}
</style>
